package cn.ljn.pet.service.impl;

import cn.ljn.basic.util.*;
import cn.ljn.org.domain.Shop;
import cn.ljn.org.mapper.ShopMapper;
import cn.ljn.pet.domain.SearchMasterMsg;
import cn.ljn.pet.domain.SearchMasterMsgAuditLog;
import cn.ljn.pet.dto.SearchMasterMsgDto;
import cn.ljn.pet.mapper.PetMapper;
import cn.ljn.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.ljn.pet.mapper.SearchMasterMsgMapper;
import cn.ljn.pet.service.ISearchMasterMsgService;
import cn.ljn.basic.service.impl.BaseServiceImpl;
import cn.ljn.user.domain.Logininfo;
import cn.ljn.user.domain.User;
import cn.ljn.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljn
 * @since 2023-03-16
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private PetMapper petMapper;
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsgDto dto) {
        // 校验参数
        // 保存SearchMasterMsg参数
        SearchMasterMsg searchMasterMsg = new SearchMasterMsg();
        BeanUtils.copyProperties(dto,searchMasterMsg);
        Logininfo logininfo = LoginContext.getUserInfo().getLogininfo();
        User user = userMapper.findByLogininfoId(logininfo.getId());
        searchMasterMsg.setState(0);
        searchMasterMsg.setUserId(user.getId());
        super.add(searchMasterMsg);

        // 默认通过 - 修改状态
        searchMasterMsg.setState(1);

        // 百度AI审核
        if (!BaiduAuditUtils.TextCensor(searchMasterMsg.getName())){
            // 未通过保存进日志
            SearchMasterMsgAuditLog msgAuditLog = new SearchMasterMsgAuditLog();
            msgAuditLog.setState(2);
            msgAuditLog.setAuditTime(new Date());
            msgAuditLog.setAuditId(-1L);
            msgAuditLog.setMsgId(searchMasterMsg.getId());
            msgAuditLog.setNote("审核失败：名称不合规"+dto.getName());
            searchMasterMsgAuditLogMapper.add(msgAuditLog);
            searchMasterMsg.setState(2);
        }
        // 审核通过
        // 找店铺
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.findAll());
        if(nearestShop != null){
            searchMasterMsg.setShopId(nearestShop.getId());
        }

        // 通过修改状态
        searchMasterMsgMapper.update(searchMasterMsg);

        return AjaxResult.me().success();
    }
}
